<?php
class ActionInvoice extends CAction
{
	public function run()			//Добавить возможно в будущем проверку прав, хотя должно проверять права на акшен и все правильно
	{
		$user=User::model()->findbyPk(Yii::app()->user->id);
		if (1) {	//проверка пользователя
			$model=new Invoice;
			
			//Performs the AJAX validation.
			if(isset($_POST['ajax']) && $_POST['ajax']==='invoice-form')
			{
				echo CActiveForm::validate($model);
				Yii::app()->end();
			}
			
			$showPreview=0;
			if(isset($_POST['Invoice']))
			{
				$model->attributes=$_POST['Invoice'];
				
				$model->user_id = $user->id;
				$model->contract = $user->contract; 
				$model->username = $user->username;
				
				if($model->validate()) {
					$showPreview=1;
					if (isset($_POST['print']) && $_POST['print']) {		//FIXME Печать
						$this->controller->layout='';
						$model->number = $model->nextId;
						$model->save();
						$showPreview=2;
					}
				}
			} else	{

				$model->user_id = $user->id;
				$model->contract = $user->contract; 
				$model->username = $user->username;
				$model->cost = Payacc::getTotalCost(null, null, $user->id);
			}

			if (!isset($model->number)) $model->number = '###';
			$this->controller->render('/invoice/show',array(
				'model'=>$model,
				'showPreview'=>$showPreview,
			));
		} else throw new CHttpException(404,'The requested page does not exist.');
	}

}